const modulesConfig = require('./modulesConfig.js');
const api = require('../../utils/api.js');
const wxStore = getApp().globalData.wx_store;
const page = Page;
page({
  onLoad: function(options) {
    console.log('wx_store:', wxStore);
    wxStore.setter(22);
    wxStore.setter(33);
    wxStore.setter(44);
    api.request();
    this.objectToArray(modulesConfig);
  },
  onReachBottom() {
    this.infinite_down_pull();
  },
  data: {
    modules: [],
  },

  objectToArray(obj) {
    const keys = Object.keys(obj);
    const length = keys.length;
    const modules = [];
    for (let i = 0; i < length; i++) {
      modules.push(obj[keys[i]]);
    }
    this.setData({modules});
  },

  /**
   * 生成module-1模块所需数据
   * @param {array} target
   * @return {array}
   */
  generateMoudle_1_data(target) {
    const srcList = ['../../images/goods1.jpg',
      '../../images/goods2.jpg',
      '../../images/goods3.jpg'];
    const goodsAbstract = ['Mixxtail魅夜 专业鸡尾酒 蓝色幻想鸡尾酒（露酒）310ml',
      '曼可顿面包 香蕉牛奶味 68g', '康师傅蜂蜜绿茶 500ml'];
    /**
     * @param {*} arr
     * @return {*}
     */
    function randomSelect(arr) {
      const num = Math.floor(Math.random() * arr.length);
      return arr[num];
    }

    for (let i = 0; i < 12; i++) {
      const price = (Math.random() * 20).toFixed(2);
      target.push({
        src: randomSelect(srcList),
        goods_abstract: randomSelect(goodsAbstract),
        price: price,
        discounted_price: (price * 0.5).toFixed(2),
        discounted: true,
      });
    }
    return target;
  },
  /**
   * 无限下拉
   */
  infinite_down_pull: function() {
    const modules = this.data.modules;
    const length = modules.length;
    for (let i = 0; i < length; i++) {
      if (modules[i].name === 'module-1') {
        if (modules[i].data.length > 40) {
          console.log('没有更多商品');
          return;
        };
        this.generateMoudle_1_data(modules[i].data);
      }
    }
    this.setData({modules});
  },
});
